/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.cache.RealTimeViewConfCache;
import com.sinodata.bsm.center.cache.TopuCatalogCache;
import com.sinodata.bsm.center.cache.TopuConfCache;
import com.sinodata.bsm.center.cache.TopuPlayOrderCache;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.performance.RealTimeService;
import com.sinodata.bsm.center.service.topo.TopoService;
import com.sinodata.bsm.center.user.UserUtil;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.vo.RealTimeViewConf;
import com.sinodata.bsm.common.vo.TopuCatalog;
import com.sinodata.bsm.common.vo.TopuConf;
import com.sinodata.bsm.common.vo.TopuPlayOrder;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author dongyushi
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-7-24 下午3:50:04          dongyushi        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class TopuConfigAction extends BaseAction<TopuConf> {

    /**
     * 
     */
    private static final long serialVersionUID = -950740594335955289L;
    @Autowired
    private TopuCatalogCache topuCatalogCache;
    @Autowired
    private TopuConfCache topuConfCache;
    @Autowired
    private TopuPlayOrderCache topuPlayOrderCache;
    @Autowired
    private RealTimeViewConfCache realTimeViewConfCache;
    @Autowired
    private TopoService topoService;
    @Autowired
    private RealTimeService realTimeService;

    public String common() {
        Object ojb = null;
        ojb.hashCode();

        List<Long> listScopeTopo = UserFunctionValidate.getTopoIdListForUser();
        Collections.sort(listScopeTopo);
        List<Long> listScopeCustomRealTimeId = UserFunctionValidate.getCustomRealTimeIdListForUser();
        Collections.sort(listScopeCustomRealTimeId);
        String userId = UserUtil.getInstance().getCurrentUserId();
        List<TopuPlayOrder> topuPlayOrderList = topuPlayOrderCache.getTopuPlayOrderByUserId(userId);
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        StringBuffer treeNodes = new StringBuffer();
        if (topuPlayOrderList != null && topuPlayOrderList.size() != 0) {
            for (TopuPlayOrder topuPlayOrder : topuPlayOrderList) {
                if (String.valueOf(topuPlayOrder.getFlag()).equals("0")) {
                    if (Collections.binarySearch(listScopeTopo, topuPlayOrder.getTopuConfId()) > -1) {
                        if (topuConfCache.get(topuPlayOrder.getTopuConfId()) != null) {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("id", String.valueOf(topuPlayOrder.getFlag()) + "_" + String.valueOf(topuPlayOrder.getTopuConfId()));
                            map.put("name", topuConfCache.get(topuPlayOrder.getTopuConfId()).getName());
                            list.add(map);
                            treeNodes.append(topuPlayOrder.getTopuConfId()).append(",");
                        }
                    }
                } else {
                    if (Collections.binarySearch(listScopeCustomRealTimeId, topuPlayOrder.getTopuConfId()) > -1) {
                        if (realTimeViewConfCache.get(topuPlayOrder.getTopuConfId()) != null) {
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("id", String.valueOf(topuPlayOrder.getFlag()) + "_" + String.valueOf(topuPlayOrder.getTopuConfId()));
                            map.put("name", realTimeViewConfCache.get(topuPlayOrder.getTopuConfId()).customName());
                            list.add(map);
                            treeNodes.append(topuPlayOrder.getTopuConfId()).append(",");
                        }
                    }
                }
            }
            if (treeNodes.length() != 0) {
                treeNodes.delete(treeNodes.lastIndexOf(","), treeNodes.length());
            }
        }
        Struts2Utils.getRequest().setAttribute("treeNodes", treeNodes);
        Struts2Utils.getRequest().setAttribute("list", list);
        return "common";
    }

    public String initTopoTree() {
        List<Long> listScopeTopo = UserFunctionValidate.getTopoIdListForUser();
        Collections.sort(listScopeTopo);
        List<Long> listScopeCustomRealTimeId = UserFunctionValidate.getCustomRealTimeIdListForUser();
        Collections.sort(listScopeCustomRealTimeId);
        String treeNodes = request.getParameter("treeNodes");
        String[] scope = treeNodes.split(",");
        Arrays.sort(scope);
        JSONArray jsonArray = new JSONArray();
        List<TopuCatalog> topoCatalogList = topuCatalogCache.findAll();
        JSONObject jsonObject = null;
        JSONArray jsonArrayChild = null;
        JSONObject jsonObjectIn = null;
        List<TopuConf> topoList = null;
        for (TopuCatalog topuCatalog : topoCatalogList) {
            Long catalogId = topuCatalog.getId();
            topoList = topuConfCache.findByCatalogId(catalogId);
            boolean flagTopo = false;
            for (TopuConf topuConf : topoList) {
                if (Collections.binarySearch(listScopeTopo, topuConf.getId()) > -1) {
                    flagTopo = true;
                    break;
                }
            }
            if (flagTopo) {
                jsonObject = new JSONObject();
                jsonObject.element("id", "catalogId_" + catalogId);
                jsonObject.element("catalog", true);
                jsonObject.element("name", topuCatalog.getName());
                jsonObject.element("pId", "catalogId_" + topuCatalog.getParent());
                jsonObject.element("open", true);
                //jsonObject.element("nocheck", true);
                jsonObject.element("topoId", "");
                jsonArrayChild = new JSONArray();
                for (TopuConf topuConf : topoList) {
                    if (Collections.binarySearch(listScopeTopo, topuConf.getId()) > -1) {
                        jsonObjectIn = new JSONObject();
                        jsonObjectIn.element("id", "0_" + topuConf.getId());
                        jsonObjectIn.element("catalog", false);
                        jsonObjectIn.element("name", topuConf.getName());
                        jsonObjectIn.element("pId", "catalogId_" + topuConf.getCatalogId());
                        if (Arrays.binarySearch(scope, String.valueOf(topuConf.getId())) > -1) {
                            jsonObjectIn.element("checked", true);
                        }
                        jsonObjectIn.element("open", true);
                        jsonObjectIn.element("topoId", topuConf.getId());
                        jsonArrayChild.add(jsonObjectIn);
                    }
                }
                jsonObject.element("children", jsonArrayChild);
                jsonArray.add(jsonObject);
            }
        }
        if (realTimeService.findAllFreeCustomView() != null && realTimeService.findAllFreeCustomView().size() != 0) {
            boolean flagCustomView = false;
            for (RealTimeViewConf realTimeViewConf : realTimeService.findAllFreeCustomView()) {
                if (Collections.binarySearch(listScopeCustomRealTimeId, realTimeViewConf.getId()) > -1) {
                    flagCustomView = true;
                    break;
                }
            }
            if (flagCustomView) {
                jsonObject = new JSONObject();
                jsonObject.element("id", "catalogId_-1");
                jsonObject.element("catalog", false);
                jsonObject.element("name", "性能图目录");
                jsonObject.element("pId", "catalogId_-1");
                jsonObject.element("open", true);
                jsonArrayChild = new JSONArray();
                for (RealTimeViewConf realTimeViewConf : realTimeService.findAllFreeCustomView()) {
                    if (Collections.binarySearch(listScopeCustomRealTimeId, realTimeViewConf.getId()) > -1) {
                        jsonObjectIn = new JSONObject();
                        jsonObjectIn.element("id", "1_" + realTimeViewConf.getId());
                        jsonObjectIn.element("catalog", false);
                        jsonObjectIn.element("name", realTimeViewConf.customName());
                        jsonObjectIn.element("pId", "catalogId_-1");
                        if (Arrays.binarySearch(scope, String.valueOf(realTimeViewConf.getId())) > -1) {
                            jsonObjectIn.element("checked", true);
                        }
                        jsonObjectIn.element("open", true);
                        jsonArrayChild.add(jsonObjectIn);
                    }
                }
                jsonObject.element("children", jsonArrayChild);
                jsonArray.add(jsonObject);
            }
        }
        Struts2Utils.renderJson(jsonArray.toString());
        return null;
    }

    @Override
    public TopuConf getModel() {
        return null;
    }

    @Override
    public String list() throws Exception {
        return null;
    }

    @Override
    public String input() throws Exception {
        return null;
    }

    @Override
    public String save() throws Exception {
        String ids = request.getParameter("ids");
        String userId = UserUtil.getInstance().getCurrentUserId();
        //先删除此用户的旧数据
        topoService.deleteTopuPlayOrderByUserId(userId);
        //清缓存
        List<TopuPlayOrder> topuPlayOrderList = topuPlayOrderCache.getTopuPlayOrderByUserId(userId);
        if (topuPlayOrderList != null) {
            List<TopuPlayOrder> newList = new ArrayList<TopuPlayOrder>();
            for (TopuPlayOrder topuPlayOrder : topuPlayOrderList) {
                TopuPlayOrder topuPlayOrder1 = new TopuPlayOrder();
                topuPlayOrder1.setId(topuPlayOrder.getId());
                newList.add(topuPlayOrder1);
            }
            for (TopuPlayOrder topuPlayOrder : newList) {
                topuPlayOrderCache.remove(topuPlayOrder.getId());
            }
        }
        if (ids != null && !ids.equals("")) {
            String[] array = ids.split(",");
            //再保存
            List<TopuPlayOrder> list = new ArrayList<TopuPlayOrder>();
            for (int i = 0; i < array.length; i++) {
                TopuPlayOrder topuPlayOrder = new TopuPlayOrder();
                topuPlayOrder.setTopuConfId(Long.valueOf(array[i].split("_")[1]));
                topuPlayOrder.setOrderby(Long.valueOf(i));
                topuPlayOrder.setUserId(userId);
                topuPlayOrder.setFlag(Integer.valueOf(array[i].split("_")[0]));
                list.add(topuPlayOrder);
            }
            topoService.saveTopuPlayOrder(list);
            //放入缓存
            for (TopuPlayOrder topuPlayOrder : list) {
                topuPlayOrderCache.put(topuPlayOrder.getId(), topuPlayOrder);
            }
        }
        renderText("true");
        return null;
    }

    @Override
    public String delete() throws Exception {
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {

    }

}
